<?php

namespace backend\controllers;

use Yii;
use backend\models\School;
use backend\models\Department;
use backend\models\Campus;
use backend\models\SchoolCertificate;
use backend\models\SchoolSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * SchoolController implements the CRUD actions for School model.
 */
class SchoolController extends Controller
{ 
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all School models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SchoolSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        // $dataProvider->query->andWhere(['not', "ZT = '修改'"]);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionAudit()
    {
        $searchModel = new SchoolSearch();
        $dataProvider = $searchModel->search(array_merge_recursive(
            Yii::$app->request->queryParams,
            ['SchoolSearch' => ['ZT'=>'待审核']]
        ));
        
        return $this->render('audit', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Displays a single School model.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $flag = \Yii::$app->request->get('flag');
        $model = $this->findModel($id);
        if($flag != NULL)
        {
            if($flag)
            {
                $model = School::find()->where("DM = '$model->DM'")->andWhere("ZT = '正常'")->one();
            }
            else
            {
                $model = School::find()->where("DM = '$model->DM'")->andWhere(['not', "ZT = '正常'"])->one();
            }
        }
        
        if(\Yii::$app->request->isPost && $model->load(\Yii::$app->request->post()))
        {
            $model->ZT = '修改';
            $model->update(false);
        }
            
        return $this->render('view', [
            'model' => $model,
        ]);
    }

    public function actionInfo($id)
    {
        $model = $this->findModel($id);
        preg_match('/\d{4}-\d{1,}/', $model->JXNY, $matches);
        $model->JXNY = $matches[0];
        return $this->render('info', [
            'model' => $model,
        ]);
    }

    /**
     * Creates a new School model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {    
        $model = new School();
        $data = Yii::$app->request->post();
        $data['School']['ZT'] = '正常';   // 刚创建的学校记录初始状态为“正常”

        if ($model->load($data) && $model->save()) {
            Department::createNewRecord($model->ID);
            Campus::createNewRecord($model->ID);
            SchoolCertificate::createNewRecord($model->ID);
            return $this->redirect(['info', 'id' => $model->ID]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing School model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            $newRecord = School::getShadowRecord($model);
            // echo '<pre>';
            // var_dump($newRecord);
            // echo '</pre>';
            // exit();
            return $this->redirect(['info', 'id' => $newRecord->ID]);
        }

        preg_match('/\d{4}-\d{1,}/', $model->JXNY, $matches);   // 从数据库读取“建校年月日”只保留年和月
        $model->JXNY = $matches[0];
        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing School model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /* 提交审核（学校用户）*/
    public function actionVerify($id)
    {
        $model = $this->findModel($id);
        $newRecord = School::getShadowRecord($model);

        if ($newRecord)
        {
            $newRecord['ZT'] = '待审核';
            $newRecord->update(false);
        }

        return $this->redirect(['info', 'id' => $newRecord->ID]);
    }

    /* 审核通过（教育部门）*/
    public function actionVerified($id)
    {
        $model = $this->findModel($id);
        $noumenon = School::updateRecord($model); // 审核通过后更新记录（返回更新后的本体记录）

        return $this->redirect(['view', 'id' => $noumenon->ID]);
    }

    /**
     * Finds the School model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return School the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = School::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
